package com.psm.controller;

import com.google.gson.Gson;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.render.JsonRender;
import com.jfinal.core.Controller;
import com.jfinal.plugin.activerecord.Model;
import com.jfinal.plugin.activerecord.Record;
import com.psm.model.*;

import org.apache.commons.lang.ArrayUtils;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by cheam on 15/6/19.
 */
public abstract class BaseController<M extends Model<M>> extends Controller {

    protected String tableName;
    protected Class<M> modelClass;

    protected M _model;

    /**yyyy-MM-dd HH:mm:ss 日期时间*/
    protected static final SimpleDateFormat dateTimeFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    /**yyyy-MM-dd 日期*/
    protected static final SimpleDateFormat dateFormat=new SimpleDateFormat("yyyy-MM-dd");
    /**yyyy年*/
    protected static final SimpleDateFormat yearFormat=new SimpleDateFormat("yyyy");
    /**MM月*/
    protected static final SimpleDateFormat monthFormat=new SimpleDateFormat("MM");
    /**dd 日*/
    protected static final SimpleDateFormat dayFormat=new SimpleDateFormat("dd");
    /**HH:mm:ss 时间*/
    protected static final SimpleDateFormat timeFormat=new SimpleDateFormat("HH:mm:ss");
    /**HH:mm 小时分钟*/
    protected static final SimpleDateFormat hmFormat=new SimpleDateFormat("HH:mm");
    /**EEE 星期*/
    protected static final SimpleDateFormat wdFormat=new SimpleDateFormat("EEE");

    protected static IdGenerater idGenerater=new IdGenerater();

    /** 获取当前系统操作人 */
    public Record getCurrentUser() {

        return SysUser.me.qryLoginUser(getCurrentUserId());

    }
    /** 获取当前系统操作人ID */
    public Long getCurrentUserId(){

        String login_user_id=getCookie("login_user_id");

        return idGenerater.to10(login_user_id);
    }

    /***
     *
     * @param state
     * @param msg
     * @param obj 数组 [0]:id [1]:tokenid
     */
    public void rendJson_(Object state,String msg,Object... obj){
        this.getResponse().setContentType("text/json;charset=UTF-8");


        Map<String,Object> json=new HashMap<String,Object>();
        json.put("success",state);
        json.put("msg",msg);
        if(obj!=null&&obj.length>0){
            json.put("obj", obj[0]);
            if(obj.length>1){
                json.put("tokenid",obj[1]);
            }
        }
        this.renderJson(json);
    }


    /**
     * 通过pid字段关联
     * @param dataList 集合
     * @param pnode 父节点
     * @param cname 节点名称字段
     */
    protected void fillTree(List<Record> dataList,TreeNode pnode,String cname,Boolean canChk,List<Long>ckidList) {
        List<TreeNode> childelist = new ArrayList<TreeNode>();
        for (Record m : dataList) {
            Long pid_ = Long.parseLong(m.get("pid").toString());
            if (pnode.getId() == pid_) {
                Long id = Long.parseLong(m.get("id").toString());
                Long pid = Long.parseLong(m.get("pid").toString());

                TreeNode nodechild = new TreeNode();
                nodechild.setId(id);
                nodechild.setPid(pid);
                nodechild.setText(m.getStr(cname));
                nodechild.setIconCls("icon-home");
                nodechild.setCanChk(canChk);
                if(null != m.get("type")){
                    nodechild.setType(m.get("type").toString());
                }
                childelist.add(nodechild);
                if(ckidList!=null&& ArrayUtils.contains(ckidList.toArray(), id))
                    nodechild.setChecked(true);
                fillTree(dataList, nodechild,cname,canChk,ckidList);
            }
        }
        if (childelist.isEmpty() == false && childelist.size() > 0) {
            pnode.setChildren(childelist);
        }
    }

    /**通过Gson生成*/
    public void renderJson_(Object obj) {
        super.renderJson(new Gson().toJson(obj));
    }


    public void sys_pa_code(){
        String table = getPara("table","");
        String field = getPara("field","");

        List<Record> list= Db.find("select * from " + SysPaCode.tableName+" where bus_table=? and bus_field=?",new Object[]{table,field});
        this.renderJson(list);
    }

    public void get_year(){
        GregorianCalendar gc=new GregorianCalendar();

        List<Record> list = new ArrayList<Record>();

        for(int i = -5;i<=5;i++){
            Record r = new Record();

            gc.setTime(new Date());
            gc.add(1, i);
            String year =  yearFormat.format(gc.getTime());

            r.set("id", year);
            r.set("text", year);

            list.add(r);
        }

        this.renderJson(list);
    }

    public List<PrintBean> getPrintList(List<Record> list,int pageSize){
        List<PrintBean> pb_list = new ArrayList<PrintBean>();
        int rows = list.size();
        int page = 0;
        if(rows%pageSize==0){
            page=rows/pageSize;
        }else{
            page=(rows/pageSize)+1;
        }

        for(int i = 1;i<=page;i++){
            int begin = (i-1)*pageSize;
            int end = i*pageSize;

            if(end>rows){
                end = rows;
            }

            PrintBean bp = new PrintBean();
            bp.setPage(i + "");
            bp.setContent(list.subList(begin, end));
            pb_list.add(bp);
        }


        return pb_list;
    }

    @Override
    public void renderJson(Object object) {
        if (isIE()) {
            render(new JsonRender(object).forIE());
        }else {
            super.renderJson(object);
        }
    }

    @Override
    public void renderJson(String jsonText) {
        if (isIE()) {
            render(new JsonRender(jsonText).forIE());
        }else {
            super.renderJson(jsonText);
        }
    }

    @Override
    public void renderJson(String[] attrs) {
        if (isIE()) {
            render(new JsonRender(attrs).forIE());
        }else {
            super.renderJson(attrs);
        }
    }

    @Override
    public void renderJson() {
        if (isIE()) {
            render(new JsonRender().forIE());
        }else {
            super.renderJson();
        }
    }

    @Override
    public void renderJson(String key, Object value) {
        if (isIE()) {
            render(new JsonRender(key, value).forIE());
        }else {
            super.renderJson(key, value);
        }
    }

    /**
     * 判断是否万恶的IE
     * @return
     */
    public boolean isIE(){
        HttpServletRequest request = this.getRequest();
        String user_agent = request.getHeader("USER-AGENT");

        System.out.println("user_agent:"+user_agent);

        if (null == user_agent || "".equals(user_agent)) {
            return false;
        }
        String request_method = request.getMethod().toUpperCase();
        int msie = user_agent.toUpperCase().indexOf("MSIE");
        int ie11 = user_agent.toUpperCase().indexOf("RV");
        int ie_11 = user_agent.toString().indexOf("rv");
        System.out.println("user_agent:ie11:"+ie_11);

        return (user_agent.toUpperCase().indexOf("MSIE")>0?true:false) || (user_agent.toUpperCase().indexOf("RV")>0?true:false )|| (ie_11>0?true:false ) /*&& "POST".equals(request_method)*/;
    }

}
